package com.wchat.network.message;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;

import com.wchat.network.Configs;
import com.wchat.network.device.SendTarget;

public class MessageSender {

	private static HashMap<Integer, DatagramSocket> datagramSocketPool = new HashMap<Integer, DatagramSocket>();

	private static DatagramSocket getSenderSocket(int port) throws SocketException {
		DatagramSocket socket = datagramSocketPool.get(port);
		if (socket != null)
			return socket;
		socket = new DatagramSocket(port);
		datagramSocketPool.put(port, socket);
		return socket;
	}

	public static void send(SendTarget target, Message message) throws SocketException, IOException {
		DatagramSocket senderSocket = /*getSenderSocket(Configrations.UDP_PORT);*/ new DatagramSocket();
		byte[] bytes = message.getBytes();
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length, target.getAddress(),
				Configs.UDP_PORT);
		senderSocket.send(packet);
		senderSocket.close();
	}

}
